<?php

namespace App\Http\ControllersVer1;

use Illuminate\Http\Request;

use Uuid;

use App\Place;
use App\User;


class PlaceController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addPlace(Request $request) {

        $this->validate($request, [
            'place_name' => 'required',
            'place_address' => 'required',
            'place_latitude' => 'required',
            'place_longitude' => 'required',
        ]);

        $me = $request->user();

        $places_count = Place::where('user_id', $me->id)->count();

        if ($places_count >= 3) {
            return response()->json([
                'code' => 4060,
                'msg' => 'places count >= 3'
            ]);
        }

        $place = new Place;
        $place->user_id = $me->id;
        $place->uuid = str_replace('-', '', Uuid::generate(4)->string);
        $place->name = $request->input('place_name');
        $place->address = $request->input('place_address');
        $place->latitude = $request->input('place_latitude');
        $place->longitude = $request->input('place_longitude');
        $place->save();

//        $places = Place::where('user_id', $me->id)
//            ->orderBy('id', 'desc')
//            ->get();

        $me = User::find($me->id);

        return response()->json([
            'code' => 2000,
            //'places' => $places,
            'me' => $me,
            'msg' => 'success!'
        ]);

    }


    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function deletePlace(Request $request) {

        $this->validate($request, [
            'place_uuid' => 'required',
        ]);

        $place_uuid = $request->input('place_uuid');

        $me = $request->user();

        $place = Place::where('uuid', $place_uuid)->first();

        if (is_null($place)) {

            return response()->json([
                'code' => 40600,
                'msg' => 'wrong uuid!'
            ]);

        } else {

            if ($place->user_id == $me->id) {

                $place->delete();

            } else {

                return response()->json([
                    'code' => 40600,
                    'msg' => 'you are not the place owner!'
                ]);

            }
        }

//        $places = Place::where('user_id', $me->id)
//            ->orderBy('id', 'desc')
//            ->get();
        $me = User::find($me->id);

        return response()->json([
            'code' => 2000,
            //'places' => $places,
            'me' => $me,
            'msg' => 'success!'
        ]);

    }
}
